package com.aiYouPms.admin.controller;

import com.aiYouPms.admin.dto.MenuCreateParams;
import com.aiYouPms.admin.dto.MenuUpdateParams;
import com.aiYouPms.common.api.HttpResult;
import com.aiYouPms.common.model.Menu;
import com.aiYouPms.common.service.MenuService;
import com.aiYouPms.common.util.MenuTreeUtil;
import com.aiYouPms.common.util.MenuConverterUtil;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@ResponseBody
@RequestMapping("/menu")
public class MenuController {

    private final MenuService menuService;

    @Autowired
    public MenuController(MenuService menuService) {
        this.menuService = menuService;
    }

    /**
     * 获取所有菜单（树形结构）
     *
     * @return 树形结构菜单列表
     */
    @GetMapping("/tree")
    public HttpResult<List<Menu>> getMenuTree() {
        List<Menu> menus = menuService.findAll();
        List<Menu> menuTree = MenuTreeUtil.buildMenuTree(menus);
        return HttpResult.success(menuTree);
    }

    /**
     * 获取前端路由格式的菜单
     *
     * @return 前端路由格式的菜单列表
     */
    @GetMapping("/routes")
    public HttpResult<List<Map<String, Object>>> getMenuRoutes() {
        List<Menu> menus = menuService.findAll();
        List<Map<String, Object>> routes = MenuConverterUtil.convertToRoutes(menus);
        return HttpResult.success(routes);
    }

    /**
     * 获取所有菜单
     *
     * @return 菜单列表
     */
    @GetMapping("/list")
    public HttpResult<List<Menu>> getMenuList() {
        List<Menu> menus = menuService.findAll();
        return HttpResult.success(menus);
    }

    /**
     * 根据ID获取菜单详情
     *
     * @param id 菜单ID
     * @return 菜单详情
     */
    @GetMapping("/{id}")
    public HttpResult<Menu> getMenuById(@PathVariable Long id) {
        Menu menu = menuService.findById(id);
        if (menu == null) {
            return HttpResult.error("菜单不存在");
        }
        return HttpResult.success(menu);
    }

    /**
     * 根据父ID获取子菜单
     *
     * @param parentId 父菜单ID
     * @return 子菜单列表
     */
    @GetMapping("/listByParentId")
    public HttpResult<List<Menu>> getMenuByParentId(@RequestParam Long parentId) {
        List<Menu> menus = menuService.findByParentId(parentId);
        return HttpResult.success(menus);
    }

    /**
     * 创建菜单
     *
     * @param menuCreateParams 菜单创建参数
     * @return 创建结果
     */
    @PostMapping("/create")
    public HttpResult<Menu> createMenu(@Validated @RequestBody MenuCreateParams menuCreateParams) {
        try {
            Menu menu = new Menu();
            BeanUtils.copyProperties(menuCreateParams, menu);
            Menu createdMenu = menuService.create(menu);
            return HttpResult.success("创建成功", createdMenu);
        } catch (Exception e) {
            log.error("创建菜单失败", e);
            return HttpResult.error("创建失败: " + e.getMessage());
        }
    }

    /**
     * 更新菜单
     *
     * @param id               菜单ID
     * @param menuUpdateParams 菜单更新参数
     * @return 更新结果
     */
    @PostMapping("/update/{id}")
    public HttpResult<Menu> updateMenu(@PathVariable Long id,
                                       @Validated @RequestBody MenuUpdateParams menuUpdateParams) {
        try {
            Menu menu = new Menu();
            BeanUtils.copyProperties(menuUpdateParams, menu);
            Menu updatedMenu = menuService.update(id, menu);
            return HttpResult.success("更新成功", updatedMenu);
        } catch (Exception e) {
            log.error("更新菜单失败", e);
            return HttpResult.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除菜单
     *
     * @param id 菜单ID
     * @return 删除结果
     */
    @PostMapping("/delete/{id}")
    public HttpResult<String> deleteMenu(@PathVariable Long id) {
        try {
            menuService.deleteById(id);
            return HttpResult.success("删除成功");
        } catch (Exception e) {
            log.error("删除菜单失败", e);
            return HttpResult.error("删除失败: " + e.getMessage());
        }
    }
}